import { Button, DatePicker, Flex, Form, Modal, Pagination, Radio, Select, Table, TableProps } from 'antd';
import style from '../css/Outpatientregistrationstatistics.module.scss'
import { useRef, useState } from 'react';
import { RadioChangeEvent } from 'antd/lib';
import { PrinterOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { exportDataToExcel } from '../components/exportToExcel'

function Outpatientregistrationstatistics() {
    const [form] = Form.useForm();
    const [value, setValue] = useState(1);
    const [method, setMethod] = useState(1)

    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    const changemethid = (e: RadioChangeEvent) => {
        console.log('method checked', e.target.value);
        setMethod(e.target.value);
    }
    // 日期选择
    const { RangePicker } = DatePicker;
    // 表格数据
    interface DataType {
        key: string;
        methods: string;
        amount: number;
        Returnnumber: number;
        receivable: string;
        netreceipts: string;
        Refundamount: string
    }


    const columns: TableProps<DataType>['columns'] = [
        {
            title: '统计方式',
            dataIndex: 'methods',
            key: 'methods',
        },
        {
            title: '挂号总数',
            dataIndex: 'amount',
            key: 'amount',
        },
        {
            title: '退号数',
            dataIndex: 'Returnnumber',
            key: 'Returnnumber',
        },
        {
            title: '应收金额',
            key: 'receivable',
            dataIndex: 'receivable',
        },
        {
            title: '实收金额',
            key: 'netreceipts',
            dataIndex: 'netreceipts',
        },
        {
            title: '退号金额',
            key: 'Refundamount',
            dataIndex: 'Refundamount',
        },
        {
            title: '操作',
            key: 'action',
            render: () => <a onClick={()=>details()}>明细</a>
        },
    ];

    const datas: DataType[] = [
        {
            key: '1',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '2',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '3',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '4',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '5',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '6',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '7',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '8',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '9',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },
        {
            key: '10',
            methods: '门诊外科',
            amount: 200,
            Returnnumber: 5,
            receivable: '6000.00',
            netreceipts: '6000.00',
            Refundamount: '300.00'
        },

    ];

    // 汇总
    const summary=()=>{
        console.log('汇总')
        form.validateFields().then(values => {
            console.log('Validated values: ', values);
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    }
    // 重置
    const reset=()=>{
        console.log('重置')
        form.resetFields()
    }
    // 选择科室
    const getdepar=(value:string)=>{
        console.log(value)
    }
    // 打印
    const tableRef = useRef<HTMLDivElement>(null);
    const print= async ()=>{
        
        if (tableRef.current) {
            console.log('打印')
            const canvas = await html2canvas(tableRef.current);
            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF('p', 'pt', 'a4');
            const imgProps = pdf.getImageProperties(imgData);
            const pdfWidth = pdf.internal.pageSize.getWidth();
            const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
       
            pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
            pdf.save('table.pdf');
          }
    }
    // 导出
    const exports=()=>{
        console.log('导出')
        exportDataToExcel(datas,'table_datas.xlsx')
    }
    // 明细
    const details=()=>{
        console.log('明细')
        setDetailsshow(true)
    }
    const [detailsshow,setDetailsshow] = useState(false)
    // 明细对话框关闭
    const detailsCancel=()=>{
        setDetailsshow(false)
    }
    // 明细对话框表格数据
    interface ModalDateType{
        key: string | number;
        visitNumber: string;
        visitCardNumber: string;
        patientName: string;
        department: string;
        doctor: string;
        amount: number;
        status: string; 
        visitDate: Date | string; // 日期可以是 Date 对象或 ISO 格式的字符串
        visittime:string
    }
    const Modalcolumns: TableProps<ModalDateType>['columns']=[
        {
            title: '就诊号',
            dataIndex: 'visitNumber',
            key: 'visitNumber',
            width:118
        },
        {
            title: '就诊卡号',
            dataIndex: 'visitCardNumber',
            key: 'visitCardNumber',
            width:119
        },
        {
            title: '患者姓名',
            dataIndex: 'patientName',
            key: 'patientName',
            width:109
        },
        {
            title: '挂号科室',
            dataIndex: 'department',
            key: 'department',
            width:127
        },
        {
            title: '挂号医生',
            dataIndex: 'doctor',
            key: 'doctor',
            width:107
        },
        {
            title: '挂号金额',
            dataIndex: 'amount',
            key: 'amount',
            render: (text) => `¥${text.toFixed(2)}`,
            width:104
        },
        {
            title: '挂号状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => (
                <div style={{
                    display: 'flex',
                    alignItems: 'center'
                }}>
                    <p className={text == '待就诊' ? style.bluestatus : text == '已就诊' ? style.greenstatus : text == '已退号' ? style.orengestatus : style.graystatus} style={{
                        width: 8,
                        height: 8,
                        borderRadius: '50%',
                        marginRight: 5
                    }}></p>
                    <span>{text}</span>
                </div>
            )  
            ,
            width:89
        },
        {
            title: '挂号日期',
            dataIndex: 'visitDate',
            key: 'visitDate',
            render: (text) => (typeof text === 'string' ? new Date(text).toLocaleDateString() : text.toLocaleDateString()),
            width:210
        },
        {
            title: '挂号时间',
            dataIndex: 'visittime',
            key: 'visittime',
            render: (text) => (typeof text === 'string' ? new Date(text).toLocaleDateString() : text.toLocaleDateString()),
            width:182
        },
    ]
    const ModalDatas:ModalDateType[]=[
        {
            key: '1',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '待就诊',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '2',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已就诊',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '3',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已退号',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '4',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已退号',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '5',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已退号',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '6',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已失效',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '7',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已失效',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '8',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已就诊',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '9',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '已就诊',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
        {
            key: '10',
            visitNumber: '6520050869',
            visitCardNumber: '1234567890',
            patientName: '张三',
            department: '内科',
            doctor: '李医生',
            amount: 30,
            status: '待就诊',
            visitDate: '2024-01-06  08:00-09:00', // 这里应该是一个能被 Date 构造器解析的字符串，或者直接是一个 Date 对象
            visittime:'2024-01-06  09:20:30'
        },
    ]
    return (
        <>
            <Modal
                title='挂号明细'
                open={detailsshow}
                footer={false}
                width={930}
                onCancel={detailsCancel}
            >
                <Table<ModalDateType>
                    columns={Modalcolumns}
                    dataSource={ModalDatas}
                    scroll={{ x: 'max-content' }}
                    className={style.Modaltable}   
                    pagination={false} 
                ></Table>
                <Pagination style={{ marginTop: 20 }} defaultCurrent={2} total={55} showSizeChanger={false} showTotal={(total) => `共 ${total} 条数据`} align="end" />
            </Modal>
            <div className={style.searchboxs}>
                <Form
                    form={form}
                    initialValues={{ timetype: value, Statisticalmethod: method }}
                >
                    <Flex>
                        <Form.Item label='时间类型' name='timetype' className={style.itemstyle}>
                            <Radio.Group onChange={onChange} >
                                <Radio value={1}>按天</Radio>
                                <Radio value={2}>按周</Radio>
                                <Radio value={3}>按月</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item style={{ marginLeft: 40 }} label='时间范围' rules={[{required:true}]} name='timerange' className={style.itemstyle}>
                            <RangePicker allowClear style={{ width: 305, height: 32 }} />
                        </Form.Item>
                    </Flex>
                    <Flex justify='space-between'>
                        <Form.Item label='统计方式' name='Statisticalmethod' className={style.itemstyle}>
                            <Radio.Group onChange={changemethid}>
                                <Radio value={1}>按科室</Radio>
                                <Radio value={2}>按医生</Radio>
                                <Radio value={3}>按支付方式</Radio>
                                <Radio value={4}>按收费员</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item >
                            <Button onClick={()=>reset()} style={{ width: 61, height: 32, borderRadius: 0 }}>重置</Button>
                            <Button onClick={()=>summary()} type="primary" style={{ width: 75, height: 32, borderRadius: 0, marginLeft: 10 }} icon={<SearchOutlined />}>
                                汇总
                            </Button>
                        </Form.Item>
                    </Flex>
                </Form>
            </div>
            <div className={style.datalists}>
                <Form
                    form={form}
                    style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
                    initialValues={{ depart: '全部' }}
                >
                    <Form.Item label='科室' name='depart'>
                        <Select
                            style={{ width: 200, height: 32 }}
                            allowClear
                            onChange={getdepar}
                            options={[
                                { value: '全部', label: '全部' },
                                { value: '门诊外科', label: '门诊外科' },
                                { value: '儿科', label: '儿科' },
                                { value: '骨科', label: '骨科' },
                                { value: '耳鼻喉科', label: '耳鼻喉科' },
                                { value: '眼科', label: '眼科' },
                                { value: '门诊内科', label: '门诊内科' },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button onClick={()=>print()} style={{ width: 75, height: 32, marginRight: 10, borderRadius: 0, color: '#0468ff', borderColor: '#0468ff' }} icon={<PrinterOutlined />}>打印</Button>
                        <Button onClick={()=>exports()} style={{ width: 75, height: 32, borderRadius: 0, color: '#0468ff', borderColor: '#0468ff' }} icon={<UploadOutlined />}>导出</Button>
                    </Form.Item>
                </Form>
                <div ref={tableRef}>
                    <Table<DataType>
                        
                        className={style.tabledata}
                        columns={columns}
                        dataSource={datas}
                        pagination={false}
                        summary={(pageData) => {
                            let totalBorrow = 0;
                            let totalRepayment = 0;
                            let totalreceivable = 0;
                            let totalnetreceipts = 0;
                            let totalRefundamount = 0;
                            pageData.forEach(({ amount, Returnnumber, receivable, netreceipts, Refundamount }) => {
                                totalBorrow += amount;
                                totalRepayment += Returnnumber;
                                totalreceivable += Number(receivable)
                                totalnetreceipts += Number(netreceipts)
                                totalRefundamount += Number(Refundamount)
                            });
                            return (
                                <>
                                    <Table.Summary.Row style={{ fontWeight: 700 }}>
                                        <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
                                        <Table.Summary.Cell index={1}>
                                            <span>{totalBorrow}</span>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={2}>
                                            <span>{totalRepayment}</span>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={3}>
                                            <span>￥{totalreceivable.toFixed(2)}</span>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={4}>
                                            <span>￥{totalnetreceipts.toFixed(2)}</span>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={5}>
                                            <span style={{ color: 'rgba(255, 100, 100, 0.996078431372549)' }}>￥{totalRefundamount.toFixed(2)}</span>
                                        </Table.Summary.Cell>
                                        <Table.Summary.Cell index={6}>
                                            <span></span>
                                        </Table.Summary.Cell>
                                    </Table.Summary.Row>
                                </>
                            );
                        }}
                    />
                </div>
                <Pagination style={{ marginTop: 20 }} showQuickJumper defaultCurrent={2} total={300} showTotal={(total) => `共 ${total} 条数据`} align="end" />
            </div>
        </>
    );
}

export default Outpatientregistrationstatistics;